#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include "Mutex.hpp"
using namespace MutexMod;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int ticket = 1000;
class ThreadData
{
public:
    ThreadData(const std::string &name, Mutex *_lock)
        : _name(name),
          locky(_lock)
    {
    }
    std::string _name;
    Mutex *locky;
};

void *route(void *arg)
{
    char *id1 = (char *)arg;
    // ThreadData *id = static_cast<ThreadData *>(arg);
    while (1)
    {
        pthread_mutex_lock(&lock);
        // id->locky->lock();
        // 一次执行完成后会自动析构，不需要手动释放
        // MutexProtect mp(id->locky);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", id1, ticket);
            ticket--;
            pthread_mutex_unlock(&lock);
            // id->locky->unlock();
        }
        else
        {
            break;
        }
    }
    return nullptr;
}
int main(void)
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr); // 初始化锁

    Mutex lock;
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread-1", &lock);
    ThreadData *td2 = new ThreadData("thread-2", &lock);
    ThreadData *td3 = new ThreadData("thread-3", &lock);
    ThreadData *td4 = new ThreadData("thread-4", &lock);

    pthread_create(&t1, NULL, route, td1);

    pthread_create(&t2, NULL, route, td2);

    pthread_create(&t3, NULL, route, td3);

    pthread_create(&t4, NULL, route, td4);

    // pthread_create(&t1, NULL, route, &lock);

    // pthread_create(&t2, NULL, route, &lock);

    // pthread_create(&t3, NULL, route, &lock);

    // pthread_create(&t4, NULL, route, &lock);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    // pthread_mutex_destroy(&lock);
    return 0;
}